from goods.models import GoodsChannel
"""
          { 
              1: {
                  'channels': [cat1-1, cat1-2,...]  第一组里面的所有一级数据
                  'sub_cats': [cat2-1, cat2-2]   用来装所有二级数据, 在二级中再包含三级数据cat2-1.cat_subs = cat3
                  },

              2: {
                  'channels': [cat1-1...],
                  'sub_cats': [...]
                  }


          }
          """


def get_categories():
    # 查询商品频道和分类
    categories = {}  # 装所有商品类别数据
    # 获取所有一级类别数据
    channels_qs = GoodsChannel.objects.all().order_by('group_id', 'sequence')
    for channel in channels_qs:
        group_id = channel.group_id  # 获取组号
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}
        # 获取一级类别数据对象
        cat1 = channel.category
        cat1.url = channel.url
        categories[group_id]['channels'].append(cat1)  # 添加cat1一级类别数据

        # 获取所有二级类别数据, 模型类定义中related_name指明父级查询子级数据的语法
        cat2_qs = cat1.subs.all()
        for cat2 in cat2_qs:
            cat3_qs = cat2.subs.all()
            cat2.sub_cats = cat3_qs
            categories[group_id]['sub_cats'].append(cat2)

    return categories
